package com.zbkj.crmeb.chant.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.crmeb.chant.dao.ReserveMoneyDetailDao;
import com.zbkj.crmeb.chant.model.ChannelMerchantAccount;
import com.zbkj.crmeb.chant.model.ReserveMoneyDetail;
import com.zbkj.crmeb.chant.service.IChannelMerchantAccountService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.chant.service.ReserveMoneyDetailService;
import com.zbkj.crmeb.enums.AccountFlowTypeEnum;
import com.zbkj.crmeb.enums.CurrencyEnum;
import com.zbkj.crmeb.enums.OrderStatusEnum;
import com.zbkj.crmeb.store.model.PurchaseGoods;
import com.zbkj.crmeb.store.response.SupplierInfo;
import com.zbkj.crmeb.store.service.AccountFlowService;
import com.zbkj.crmeb.system.service.SystemAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

@Service
@Slf4j
public class ReserveMoneyDetailServiceImpl extends ServiceImpl<ReserveMoneyDetailDao, ReserveMoneyDetail> implements ReserveMoneyDetailService {

    @Autowired
    private IChannelMerchantAccountService channelMerchantAccountService;
    @Autowired
    private AccountFlowService accountFlowService;
    @Autowired
    private SystemAdminService systemAdminService;
    @Autowired
    private IChannelMerchantService channelMerchantService;

    @Override
    public Boolean saveReserveMoneyDetail(Integer merId, Integer purchaseId, String purchaseOrderId, BigDecimal purchasePrice, BigDecimal reserveMoney, String message) {
        ReserveMoneyDetail detail = new ReserveMoneyDetail();
        detail.setMerId(merId);
        detail.setPurchaseId(purchaseId);
        detail.setPurchaseOrderId(purchaseOrderId);
        detail.setPurchasePrice(purchasePrice);
        detail.setReserveMoney(reserveMoney);
        detail.setMessage(message);
        detail.setOperateId(systemAdminService.getAdminId());
        return this.save(detail);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void calcReserveMoney(PurchaseGoods purchaseGoods, CurrencyEnum currency, Integer merId, Integer id, String ip) {
        SupplierInfo supplierInfo = channelMerchantService.getSupplierInfo(merId);
        BigDecimal closePrice = Objects.equals(purchaseGoods.getStatus(), OrderStatusEnum.CANCEL.getCode()) || Objects.equals(purchaseGoods.getStatus(), OrderStatusEnum.REJECTED_SUCCESS.getCode()) ? purchaseGoods.getRefundPrice() : purchaseGoods.getGoodsPrice();
        BigDecimal reserveMoney = channelMerchantAccountService.calReserveMoney(supplierInfo.getSupplierId(), closePrice.negate());
        // 备用金足够时 自动结算，生成采购记录
        if (reserveMoney.compareTo(BigDecimal.ZERO) > 0) {
            saveReserveMoneyDetail(merId, purchaseGoods.getId(), purchaseGoods.getChannelOrderSn(), closePrice, reserveMoney, closePrice.compareTo(BigDecimal.ZERO) > 0 ? "自动结算" : "变更供应商退回/供应商取消订单退回");

            if (Objects.nonNull(currency) && !currency.equals(CurrencyEnum.CN)) {
                closePrice = closePrice.divide(purchaseGoods.getExchangeRate(), 2, RoundingMode.UP);
            }
            ChannelMerchantAccount channelMerchantAccount = new ChannelMerchantAccount();
            channelMerchantAccount.setMerId(merId);
            channelMerchantAccount.setAccount(closePrice.negate());
            channelMerchantAccount.setCloseMoney(closePrice);
            channelMerchantAccountService.calcMoney(channelMerchantAccount);
            accountFlowService.saveAccountFlow(merId, id, systemAdminService.getAdminId(), ip, AccountFlowTypeEnum.PRODUCT, closePrice.negate(), null, null, "结算订单");
            purchaseGoods.setSettlementStatus(1);
        }
    }

    @Override
    public Boolean checkSupplierAutoSettlement(Integer purchaseId, Integer merId) {
        ReserveMoneyDetail one = this.getOne(Wrappers.<ReserveMoneyDetail>lambdaQuery().eq(ReserveMoneyDetail::getPurchaseId, purchaseId)
                .eq(ReserveMoneyDetail::getMerId, merId)
                .eq(ReserveMoneyDetail::getMessage, "自动结算")
                .last("limit 1"));
        return Objects.nonNull(one);
    }
}
